﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartSpace.Workflow
{
    public partial class WorkflowService
    {
        internal InstanceState GetInstanceState(WorkflowDbContext context, string refModule, Guid refId)
        {
            InstanceState state = new InstanceState();
            WorkflowInstance instance = context.Set<WorkflowInstance>().Where(p => p.RefModule == refModule && p.RefId == refId).SingleOrDefault();
            state.IntanceId = instance.Id;
            state.RefId = refId;
            state.RefModule = refModule;
            state.WorkflowId = instance.WorkflowId;
            List<WorkflowStep> activeSteps = context.Set<WorkflowStep>().Where(p => p.InstanceId == instance.Id && p.IsActive).ToList();
            if (activeSteps.Count == 0)
            {
                ActivityMetadata activity = context.Set<ActivityMetadata>()
                    .Join(context.Set<WorkflowStep>().Where(p => p.InstanceId == instance.Id && p.IsFinal),
                        l=>l.Id,
                        r=>r.ActivityId,
                        (l,r)=>l).SingleOrDefault();
                state.StatusText = activity.Caption;
                state.StatusCode = activity.Code;
            }
            else
            {
                Guid activityId = activeSteps[0].ActivityId;
                ActivityMetadata activity = context.Set<ActivityMetadata>().Where(p => p.Id == activityId).SingleOrDefault();
                state.StatusText = activity.Caption;
                state.StatusCode = activity.Code;
            }
            return state;
        }
    }
}
